# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Maintainer: Jakub Jirutka <jakub@jirutka.cz>
pkgname=binaryen
pkgver=119
pkgrel=0
pkgdesc="Compiler infrastructure and toolchain library for WebAssembly, in C++"
url="https://github.com/WebAssembly/binaryen"
arch="all !s390x"
license="Apache-2.0"
makedepends="
	clang
	cmake
	python3
	samurai
	"
checkdepends="
	filecheck
	gtest-dev
	llvm-test-utils
	nodejs
	"
subpackages="$pkgname-dev"
# test/spec/testsuite submodule
_testsuite_gitrev=e05365077e13a1d86ffe77acfb1a835b7aa78422
source="https://github.com/WebAssembly/binaryen/archive/version_$pkgver/binaryen-$pkgver.tar.gz
	https://github.com/WebAssembly/testsuite/archive/$_testsuite_gitrev/binaryen-testsuite-$_testsuite_gitrev.tar.gz
	use-system-gtest.patch
	"
builddir="$srcdir/$pkgname-version_$pkgver"

prepare() {
	rmdir test/spec/testsuite
	mv "$srcdir"/testsuite-$_testsuite_gitrev test/spec/testsuite

	default_prepare
}

build() {
	case "$CARCH" in
	arm*|aarch64|riscv64|loongarch64)
		export CFLAGS="${CFLAGS/-fstack-clash-protection}"
		export CXXFLAGS="${CFLAGS/-fstack-clash-protection}"
		;;
	esac

	CC=clang \
	CXX=clang++ \
	LDFLAGS="$LDFLAGS -Wl,-z,stack-size=0x100000" \
	cmake -G Ninja -B build \
		-DCMAKE_BUILD_TYPE=Release \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DCMAKE_INSTALL_LIBDIR=lib \
		-DCMAKE_VERBOSE_MAKEFILE=ON \
		-DBUILD_SHARED_LIBS=ON \
		-DBUILD_TESTS=$(want_check && echo ON || echo OFF)
	cmake --build build
}

check() {
	# Tests are extremely chatty.
	msg 'running tests with stdout/stderr redirected into ./check.log...'
	python3 check.py --binaryen-bin build/bin > check.log 2>&1 || {
		echo 'tests failed, printing last 1000 lines of check.log:' >&2
		tail -n 1000 check.log

		case "$CARCH" in
			# XXX: Ignore test failures on 32-bit arches (broken tests),
			#  ppc64le and riscv64.
			arm* | ppc64le | riscv64 | x86) return 0;;
			*) return 1;;
		esac
	}
}

package() {
	DESTDIR="$pkgdir" cmake --install build
}

dev() {
	default_dev

	# XXX: doesn't exist on riscv64
	amove usr/bin/binaryen-unittests || true
}

sha512sums="
c49053cbdfdabd33dda1e04d2b50761b92b24245d6b8d9c9fec242f35624d57e6d346f54b764fdccfa07fb1b5617df3b6c535fc2cde56f619899394b2a4e3f1c  binaryen-119.tar.gz
5bd5ea065eb2680906db3f6d34a4ae39a4458ef2bda0dd8551ab465477aa998a9254c51de807b26902dbc165ed628c663b6e0a150c6d421b5f14f1da2599e746  binaryen-testsuite-e05365077e13a1d86ffe77acfb1a835b7aa78422.tar.gz
ea332616e91c7674c471eb8f8b6352c6d342a17e2b2fd585c6c2b10de89e1be74e63fe42d908af5b2e109d043085e4300905e4efb2ec57bd275db643b22e167d  use-system-gtest.patch
"
